//
//  LKBasicSettingViewController.m
//  Mideleague_Shop
//
//  Created by Zhiwang on 2020/7/15.
//  Copyright © 2020 Zhiwang. All rights reserved.
//

#import "LKBasicSettingViewController.h"
#import "LKMyShopOpenRateSettingCell.h"
#import "LKRateSegmentCell.h"
#import "LKForgetSecrectViewController.h"
@interface LKBasicSettingViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)LKBaseTableview *tableView;
@property(nonatomic,strong)NSArray *titlesArray;
@end

@implementation LKBasicSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"设置";
    self.titlesArray = @[@"更换手机号",@"修改登录密码",@"清理缓存"];
    [self createTableview];
    LKBaseButton *bottomBtn = [LKBaseButton buttonWithFrame:CGRectMake(0, 0, 64, 24) type:UIButtonTypeCustom title:@"退出登录" titleColor:[UIColor whiteColor] layercorne:25 font:[UIFont fontWithName:@"PingFangSC-Regular" size: 16] backgroudColor:[UIColor redColor] AndActionBlock:^(UIButton * _Nonnull btn) {
        [LKUserInforTool noAccount];
        [LKSwitchRootVcTool switchRootController];
    }];
    [self.view addSubview:bottomBtn];
    [bottomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).offset(-30);
        make.height.mas_equalTo(50);
        make.left.equalTo(self.view).offset(30);
        make.centerX.equalTo(self.view.mas_centerX);
    }];
    [self.view bringSubviewToFront:bottomBtn];
    // Do any additional setup after loading the view.
}
-(void)createTableview{
    self.tableView = [LKBaseTableview setTableviewWithFrame:CGRectZero style:UITableViewStyleGrouped registercellClasss:@[@"LKMyShopOpenRateSettingCell",@"LKRateSegmentCell"]];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _tableView.backgroundColor = viewDefualtColor;
    [self.view addSubview:_tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(NAVIGATION_BAR_HEIGHT);
        make.bottom.equalTo(self.view).offset(0);
    }];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
    self.tableView.scrollEnabled = NO;
    [self.tableView reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        LKRateSegmentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKRateSegmentCell"];
        cell.customSwitch.tag = 10000;
        cell.header = @"语音播报";
        if ([[LKUserInforTool account].voice_open integerValue]) {
            [cell.customSwitch setOn:YES];
        }else{
            [cell.customSwitch setOn:NO];
        }
        [cell.customSwitch addTarget:self action:@selector(switchTypeChange:) forControlEvents:UIControlEventValueChanged];
        return cell;
    }
    if (indexPath.section == 1) {
        LKRateSegmentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKRateSegmentCell"];
        cell.customSwitch.tag = 10001;
        cell.header = @"云喇叭播报";
        if ([[LKUserInforTool account].cloud_voice integerValue]) {
            [cell.customSwitch setOn:YES];
        }else{
            [cell.customSwitch setOn:NO];
        }

        [cell.customSwitch addTarget:self action:@selector(switchTypeChange:) forControlEvents:UIControlEventValueChanged];
        return cell;
    }
    LKMyShopOpenRateSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKMyShopOpenRateSettingCell"];
    cell.headerLabel.text =self.titlesArray[indexPath.section - 2];
    cell.textField.hidden = YES;
    cell.percentLabelHidden = YES;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    if (indexPath.section == 4) {
        cell.textField.hidden = NO;
        cell.accessoryType = UITableViewCellAccessoryNone;
        [cell.textField mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(cell.contentView.mas_right).offset(-20);
            make.centerY.equalTo(cell.contentView.mas_centerY);
        }];
        cell.textField.enabled = NO;
        cell.textField.textAlignment = NSTextAlignmentRight;
        cell.textField.text = [NSString stringWithFormat:@"%.f%@",[self folderSize],@"M"];
        
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60.0f;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *header = [[UIView alloc] init];
    for (UIView *subViews in header.subviews) {
        [subViews removeFromSuperview];
    }
    if (section == 2) {
        LKBaseLabel *headerLabel = [LKBaseLabel labelWithFrame:CGRectZero text:@"当顾客付款成功时，将收到该通知" textColor:COLOR_HEX(0x666666) font:[UIFont fontWithName:@"PingFangSC-Regular" size:16] textAlignment:NSTextAlignmentLeft];
        [header addSubview:headerLabel];
        [headerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(header);
            make.left.equalTo(header).offset(10);
        }];
    }
    if (section == 3) {
        LKBaseLabel *headerLabel = [LKBaseLabel labelWithFrame:CGRectZero text:@"更换手机号后，为您保留旧手机号关联数据" textColor:COLOR_HEX(0x666666) font:[UIFont fontWithName:@"PingFangSC-Regular" size:16] textAlignment:NSTextAlignmentLeft];
        [header addSubview:headerLabel];
        [headerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(header);
            make.left.equalTo(header).offset(10);
        }];
    }
    return header;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

     if (section == 4) {
         return 10.0f;
     }
     if (section == 2) {
         return 60.0f;
     }
    if (section == 3) {
        return 60.0f;
    }
    return 0.00000000001f;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc] init];
    if (section == 6) {
//        LKBaseLabel *footerLabel = [LKBaseLabel labelWithFrame:CGRectZero text:@"- 提交方费率 -" textColor:COLOR_HEX(0x666666) font:[UIFont fontWithName:@"PingFangSC-Regular" size:14] textAlignment:NSTextAlignmentLeft];
//        [footerView addSubview:footerLabel];
//        [footerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.centerX.equalTo(footerView);
//            make.top.equalTo(footerView).offset(10);
//        }];
//        LKBaseLabel *footerIntroLabel = [LKBaseLabel labelWithFrame:CGRectZero text:self.bottomStr textColor:COLOR_HEX(0x666666) font:[UIFont fontWithName:@"PingFangSC-Regular" size:12] textAlignment:NSTextAlignmentCenter];
//        footerIntroLabel.numberOfLines = 0;
//        [footerView addSubview:footerIntroLabel];
//        [footerIntroLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.centerX.equalTo(footerView);
//            make.top.equalTo(footerLabel.mas_bottom).offset(10);
//            make.left.equalTo(footerView).offset(20);
//        }];
//        return footerView;
    }
    return footerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
//    if (section == 4) {
//        return 120;
//    }
    return 0.0000000001f;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(weakSelf)
    if (indexPath.section == 2) {
        LKForgetSecrectViewController *forgetVc = [[LKForgetSecrectViewController alloc] initWithNibName:@"LKForgetSecrectViewController" bundle:nil];
        forgetVc.setType = LKSecrectSettingTypeChangePhone;
        [self.navigationController pushViewController:forgetVc animated:YES];
    }
    if (indexPath.section == 3) {
        LKForgetSecrectViewController *forgetVc = [[LKForgetSecrectViewController alloc] initWithNibName:@"LKForgetSecrectViewController" bundle:nil];
        forgetVc.setType = LKSecrectSettingTypeChangeScrect;
        [self.navigationController pushViewController:forgetVc animated:YES];
    }
    if (indexPath.section == 4) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"清理缓存" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
          [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
              [weakSelf removeCache];
          }]];
        dispatch_async(dispatch_get_main_queue(), ^{
              [self presentViewController:alert animated:YES completion:nil];
        });
    }
}

/// 按钮更改显示
/// @param swit 按钮
-(void)switchTypeChange:(UISwitch *)swit{
    if (swit.tag == 10000) {
        if (swit.on) {
            NSMutableDictionary *param = [[NSMutableDictionary alloc] initWithDictionary:@{@"voice_open":@"1"}];
            NSString *sign = [NSString encoingWithDic:param];
            [param setObject:sign forKey:@"sign"];
            [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:voiceUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
                
            } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                if ([responseObject[@"code"] isEqualToString:@"success"]) {
                    LKUserInfor *userInfor = [LKUserInforTool account];
                    userInfor.voice_open = @"1";
                    [LKUserInforTool saveAccount:userInfor];
                    [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                }else{
                    [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                }

            } failure:^(NSString * _Nullable errorMessage) {
                
            }];
        }else{
            NSMutableDictionary *param = [[NSMutableDictionary alloc] initWithDictionary:@{@"voice_open":@"0"}];
            NSString *sign = [NSString encoingWithDic:param];
            [param setObject:sign forKey:@"sign"];
            [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:voiceUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
                
            } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                if ([responseObject[@"code"] isEqualToString:@"success"]) {
                    LKUserInfor *userInfor = [LKUserInforTool account];
                    userInfor.voice_open = @"0";
                    [LKUserInforTool saveAccount:userInfor];
                    [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                }else{
                    [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                }

            } failure:^(NSString * _Nullable errorMessage) {
                
            }];
        }
    }else{
        if (swit.on) {
            NSMutableDictionary *param = [[NSMutableDictionary alloc] initWithDictionary:@{@"cloud_voice":@"1"}];
            NSString *sign = [NSString encoingWithDic:param];
            [param setObject:sign forKey:@"sign"];
            [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:cloduVoiceUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
                
            } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                if ([responseObject[@"code"] isEqualToString:@"success"]) {
                    [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                    LKUserInfor *userInfor = [LKUserInforTool account];
                    userInfor.cloud_voice = @"1";
                    [LKUserInforTool saveAccount:userInfor];
                }else{
                    [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                }

            } failure:^(NSString * _Nullable errorMessage) {
                
            }];
        }else{
            NSMutableDictionary *param = [[NSMutableDictionary alloc] initWithDictionary:@{@"cloud_voice":@"0"}];
            NSString *sign = [NSString encoingWithDic:param];
            [param setObject:sign forKey:@"sign"];
            [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:cloduVoiceUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
                
            } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                if ([responseObject[@"code"] isEqualToString:@"success"]) {
                    [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                    LKUserInfor *userInfor = [LKUserInforTool account];
                    userInfor.cloud_voice = @"0";
                    [LKUserInforTool saveAccount:userInfor];
                    
                }else{
                    [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                }

            } failure:^(NSString * _Nullable errorMessage) {
                
            }];
        }
    }
}

//缓存大小

-(CGFloat)folderSize{
    CGFloat folderSize = 0.0f;
     NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) firstObject];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath]; NSLog(@"文件数：%ld",files.count);
    for(NSString *path in files)
    { NSString *filePath = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",path]];
      folderSize += [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil].fileSize;
    }
    //转换为M为单位
    CGFloat sizeM = folderSize /1024.0/1024.0;
    return sizeM;
}
- (void)removeCache{
    //===============清除缓存==============
    //获取路径
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)objectAtIndex:0];
    //返回路径中的文件数组
    NSArray *files = [[NSFileManager defaultManager]subpathsAtPath:cachePath];
    NSLog(@"文件数：%ld",[files count]);
    for(NSString *p in files){
        NSError *error;
        NSString *path = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",p]];
        if([[NSFileManager defaultManager]fileExistsAtPath:path]){
            BOOL isRemove = [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
            if(isRemove) {
                LKMyShopOpenRateSettingCell *cell =(LKMyShopOpenRateSettingCell *) [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:4]];
                NSString *sizeM = [NSString stringWithFormat:@"%.fM",[self folderSize]];
                cell.textField.text = sizeM;
                cell.textField.enabled = NO;
//                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"清理缓存成功" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//                alertView.tag = 400;
//                [alertView show];
            //这里发送一个通知给外界，外界接收通知，可以做一些操作（比如UIAlertViewController）
        }
            else{
                NSLog(@"清除失败");
            }
        }
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
